<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="queryForms">
			<el-form-item label="产品名称" prop="productName">
				<el-input maxlength="20" show-word-limit v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input maxlength="20" show-word-limit v-model="queryParams.productModel" placeholder="请输入产品型号" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['erp:repairProduct:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['erp:repairProduct:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button size="mini" type="info" @click="handleBacks">返回</el-button>
			</el-col>
			<right-toolbar menuNames="repairProduct51" @changeTableData="changeTableData" :showSearch.sync="showSearch" @queryTable="getList" :columns.sync="columns"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''" class="informationTab" ref="eleTab">
			<el-table ref="table" @row-click="row_click" v-loading="loading" :data="repairProductList" @selection-change="handleSelectionChange" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55" />
				<el-table-column label="产品名称" prop="productName" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="产品编号" align="center" prop="productNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible">
					<template slot-scope="scope">
						<el-input class="displayData" v-model="scope.row.productNumber" maxlength="20" @change="updateData(scope.row)"> </el-input>
					</template>
				</el-table-column>
				<el-table-column label="3B号" align="center" prop="bNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible">
					<template slot-scope="scope">
						<el-input v-model="scope.row.bNumber" maxlength="20" @change="updateData(scope.row)"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="产品接收时间" align="center" prop="receiptTime" width="250" :show-overflow-tooltip="true" v-if="columns[4].visible">
					<template slot-scope="scope">
						<el-date-picker v-model="scope.row.receiptTime" type="date" placeholder="选择日期" @change="updateData(scope.row)"> </el-date-picker>
					</template>
				</el-table-column>
				<el-table-column label="产品数量" align="center" prop="productQuantity" min-width="100" :show-overflow-tooltip="true" v-if="columns[5].visible">
					<template slot-scope="scope">
						<el-input v-model="scope.row.productQuantity" disabled></el-input>
					</template>
				</el-table-column>
				<el-table-column label="故障模式" align="center" prop="failureMode" min-width="200" :show-overflow-tooltip="true" v-if="columns[6].visible">
					<template slot-scope="scope">
						<el-input type="textarea" autosize v-model="scope.row.failureMode" @change="updateData(scope.row)" maxlength="500"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="合同号/出库单" align="center" prop="contractNumber" min-width="200" :show-overflow-tooltip="true" v-if="columns[7].visible">
					<template slot-scope="scope">
						<el-input v-model="scope.row.contractNumber" maxlength="30" @change="updateData(scope.row)"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-hasPermi="['erp:repairProduct:edit']">修改</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['erp:repairProduct:remove']">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination54" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改返修单产品列对话框 -->
		<el-dialog v-dialogDrag :title="title" :visible.sync="openProduct" width="1400px" append-to-body :before-close="handleClose">
			<div class="userDialog">
				<div class="userLeft">
					<el-form :model="queryProduct" ref="queryProduct" size="small" :inline="true" label-width="68px">
						<el-form-item label="产品名称" prop="productName">
							<el-input style="width: 160px" maxlength="20" show-word-limit v-model="queryProduct.productName" placeholder="请输入名称" clearable @keyup.enter.native="handleQueryProduct" />
						</el-form-item>
						<el-form-item label="产品型号" prop="productModel">
							<el-input style="width: 160px" maxlength="20" show-word-limit v-model="queryProduct.productModel" placeholder="请输入型号" clearable @keyup.enter.native="handleQueryProduct" />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryProduct">搜索</el-button>
							<el-button icon="el-icon-refresh" size="mini" @click="resetQueryProduct">重置</el-button>
						</el-form-item>
					</el-form>
					<el-table row-key="id" @selection-change="handleSelectionProduct" v-loading="loadingproduct" :data="ProductList" ref="multipleTable" row-class-name="pointer" border>
						<el-table-column type="selection" width="55" align="center" />
						<el-table-column label="序号" align="center" type="index" width="55" />
						<el-table-column label="产品名称" prop="productName" min-width="80" :show-overflow-tooltip="true" />
						<el-table-column label="产品型号" prop="productModel" min-width="100" :show-overflow-tooltip="true" />
						<el-table-column label="数量" prop="num" min-width="150" align="center">
							<template slot-scope="scope">
								<el-input-number style="width: 180px" v-model="scope.row.num" :step="1" :min="1" @change="editNum(scope.row)"></el-input-number>
							</template>
						</el-table-column>
					</el-table>
					<pagination v-show="totalproduct > 0" :total="totalproduct" :page.sync="queryProduct.pageNum" :limit.sync="queryProduct.pageSize" @pagination="getProduct" />
				</div>
				<div class="userCenter">
					<div @click="setRight"><i class="el-icon-right"></i></div>
					<div @click="setLeft"><i class="el-icon-back"></i></div>
				</div>
				<div class="userRight">
					<el-table :data="selectList" height="616px" ref="rightTable" @selection-change="handleBackUser" border>
						<el-table-column type="selection" width="50" align="center" />
						<el-table-column label="序号" align="center" type="index" width="55" />
						<el-table-column label="产品名称" prop="productName" min-width="100" :show-overflow-tooltip="true" />
						<el-table-column label="产品型号" prop="productModel" min-width="120" :show-overflow-tooltip="true" />
						<el-table-column label="数量" prop="num" min-width="80" align="center" />
					</el-table>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitAddProduct">确 定</el-button>
				<el-button @click="cancelProduct">取 消</el-button>
			</div>
		</el-dialog>

		<el-dialog v-dialogDrag title="修改产品" :visible.sync="openEdit" width="900px" append-to-body>
			<el-form :model="editForm" ref="editForm" size="small" :inline="true" label-width="68px">
				<el-form-item label="产品名称" prop="productId">
					<el-select v-model="editForm.productId" @change="selectProduct">
						<el-option v-for="item in productDatas" :key="item.id" :label="item.productName + '(' + item.productModel + ')'" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitedit">确 定</el-button>
				<el-button @click="openEdit = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { updateRepair } from "@/api/repair/repair"
import { listProduct, repairProductList, listRepairProduct1, getRepairProduct, delRepairProduct, addRepairProduct, updateRepairProduct, productLists } from "@/api/repair/repairProduct"
import { mapGetters } from "vuex"
import { getcolumn } from "@/api/selectList"
export default {
	name: "repairProduct",
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			paramsId:'',
			BackSelectionUser: [],
			selectList: [],
			productDatas: [],
			editForm: { productId: "" },
			openEdit: false,
			showLimit: true,
			eleTabTop: 0, //表格容器距浏览器顶部距离
			openProduct: false,
			// 产品查询条件
			queryProduct: { pageNum: 1, pageSize: 10, productName: null, productModel: null, state: "1" },
			// 产品列表条数
			totalproduct: 0,
			loadingproduct: false,
			// 产品列表
			ProductList: [],
			// 选中的产品
			products: [],
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 返修单产品列表格数据
			repairProductList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				repairId: null,
				productId: null,
				productName: null,
				productModel: null,
				productNumber: null,
				receiptTime: null,
				approvalStatus: null,
				planFlag: null
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {},
			// 回显的数据id
			echoList: [],
			selectRow: [],
			// 列信息
			columns: [
				{ key: 0, label: `产品名称`, visible: true },
				{ key: 1, label: `产品型号`, visible: true },
				{ key: 2, label: `产品编号`, visible: true },
				{ key: 3, label: `3B号`, visible: true },
				{ key: 4, label: `产品接收时间`, visible: true },
				{ key: 5, label: `产品数量`, visible: true },
				{ key: 6, label: `故障模式`, visible: true },
				{ key: 7, label: `合同号`, visible: true }
			]
		}
	},
	created() {
		// this.paramsId = this.$route.query.id
		// this.$route.query.id && this.getSize()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		this.paramsId = this.$route.query.id
		this.$route.query.id && this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination54" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		setRight() {
			this.selectList.push(...this.selectRow)
			this.selectList = this.removeSame1(this.selectList)
			this.$refs.multipleTable.clearSelection()
		},
		// 去重
		removeSame1(arr) {
			let map = new Map()
			for (let item of arr) {
				// map.has()方法判断map中是否存在这个键
				// 不存在，则将键和值同时设置到map集合中，
				if (!map.has(item.id)) {
					map.set(item.id, item)
				}
			}
			// 返回map的值
			return [...map.values()]
		},
		handleBackUser(selection) {
			this.BackSelectionUser = selection
		},
		setLeft() {
			this.BackSelectionUser.forEach(item => {
				this.selectList.forEach((items, index) => {
					if (item.id == items.id) {
						this.selectList.splice(index, 1)
					}
				})
			})
		},
		editNum(row) {
			if (row.num) {
				this.$refs.multipleTable.toggleRowSelection(row, true)
			} else {
				this.$refs.multipleTable.toggleRowSelection(row, false)
			}
		},
		submitedit() {
			updateRepairProduct(this.editForm).then(res => {
				this.$modal.msgSuccess("修改成功")
				this.getList()
				this.openEdit = false
			})
		},
		selectProduct(e) {
			this.$forceUpdate()
			this.productDatas.forEach(item => {
				if (e == item.id) {
					this.editForm.productName = item.productName
					this.editForm.productModel = item.productModel
				}
			})
		},
		handleEdit(row) {
			this.editForm.id = row.id
			this.editForm.productId = row.productId
			productLists().then(res => {
				this.openEdit = true
				this.productDatas = res.rows
			})
		},
		focusData(row) {
			row.showLimit = false
		},
		blurData(row) {
			row.showLimit = true
		},
		handleBacks() {
      	const obj = { path: this.$route.path }
			this.$tab.closePage(obj).then(() => {
				this.$router.push({
					path: "/repair/repair_menu",
					query: {
						queryData: this.$route.query.queryParams
					}
				})
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		updateData(row) {
			updateRepairProduct(row).then(res => {
				this.$modal.msgSuccess("修改成功")
				this.getList()
			})
		},
		submitAddProduct() {
			let data = []
			this.selectList.forEach(item => {
				data.push({
					productId: item.id,
					productQuantity: 1,
					receiptTime: this.$route.query.receptionTime,
					state: item.state,
					remark: item.remark,
					productTypeId: item.productTypeId,
					productName: item.productName,
					productModel: item.productModel,
					productHour: item.productHour,
					num: item.num,
					currentVersionId: item.currentVersionId
				})
				item.productId = item.id
				item.productQuantity = 1
				item.receiptTime = this.$route.query.receptionTime
				delete item.id
			})
			updateRepair({ id:this.paramsId, trepairProductList: data }).then(res => {
				this.$modal.msgSuccess("新增成功")
				this.getList()
				this.openProduct = false
			})
		},
		// 点击dialog右上角关闭图标，隐藏dialog框时触发。
		handleClose(down) {
			this.$refs.multipleTable.clearSelection()
			down()
		},
		cancelProduct() {
			this.$refs.multipleTable.clearSelection()
			this.openProduct = false
		},
		handleSelectionProduct(selection) {
			this.selectRow = selection
			this.selectRow.forEach(item => {
				this.ProductList.forEach((items, index) => {
					if (item.id == items.id) {
						this.ProductList[index].num = this.ProductList[index].num || 1
					}
				})
			})
		},
		// // 选择关联产品：打勾或取消
		// handleSelectionProduct(selecteds, row) {
		// 	if (!this.echoList.includes(row.id)) {
		// 		// 回显数据里没有本条，把这条加进来(选中)
		// 		this.echoList.push(row.id)

		// 		this.selectRow.push(row)
		// 	} else {
		// 		// 回显数据里有本条，把这条删除(取消选中)
		// 		this.echoList.forEach((id, index) => {
		// 			if (id === row.id) {
		// 				this.echoList.splice(index, 1)
		// 				this.selectRow.splice(index, 1)
		// 			}
		// 		})
		// 	}
		// },
		// // 全选、取消全选
		// handleAllChange(selecteds) {
		// 	if (selecteds.length > 0) {
		// 		selecteds.forEach(item => {
		// 			if (!this.echoList.includes(item.id)) {
		// 				this.echoList.push(item.id)
		// 				this.selectRow.push(item)
		// 			}
		// 		})
		// 	} else {
		// 		this.ProductList.forEach(item => {
		// 			this.echoList.forEach((id, index) => {
		// 				if (id === item.id) {
		// 					this.echoList.splice(index, 1)
		// 					this.selectRow.splice(index, 1)
		// 				}
		// 			})
		// 		})
		// 	}
		// },
		resetQueryProduct() {
			this.resetForm("queryProduct")
			this.handleQueryProduct()
		},
		handleQueryProduct() {
			this.queryProduct.pageNum = 1
			this.getProduct()
		},
		// 查询新增弹框的列表
		getProduct() {
			this.loadingproduct = true
			listProduct(this.queryProduct).then(response => {
				this.ProductList = response.rows
				this.totalproduct = response.total
				this.loadingproduct = false
				// this.$nextTick(() => {
				// 	this.ProductList.forEach(item => {
				// 		// 在当前分页列表中查询与回显数据是否有一致的id，一致则勾选数据回显
				// 		// toggleRowSelection(item, true)：设置当前行数据为选中状态
				// 		if (this.echoList.includes(item.id)) {
				// 			this.$refs.multipleTable.toggleRowSelection(item, true)
				// 		}
				// 	})
				// })
			})
		},
		/** 查询返修单产品列列表 */
		getList() {
			this.loading = true
			this.queryParams.repairId = this.paramsId
			listRepairProduct1(this.queryParams).then(response => {
				response.rows.forEach(item => {
					item.showLimit = true
				})
				this.repairProductList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				repairId: null,
				productId: null,
				productName: null,
				productModel: null,
				productNumber: null,
				receiptTime: null,
				approvalStatus: null,
				planFlag: null,
				remark: null
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},

		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.getProduct()
			this.selectList = []
			this.openProduct = true
			this.title = "添加返修单产品"
		},
		getrepairProductList() {
			return new Promise((resolve, reject) => {
				repairProductList(this.paramsId).then(res => {
					// 筛选回显数据的id，生成数组，根据id来勾选数据
					this.echoList = res.rows.map(item => item.productId)
					this.selectRow = res.rows
					resolve()
				})
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除返修单产品数据项？")
				.then(function () {
					return delRepairProduct(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => {})
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"erp/repairProduct/export",
				{
					...this.queryParams
				},
				`repairProduct_${new Date().getTime()}.xlsx`
			)
		}
	}
}
</script>
<style lang="scss" scoped>
.userDialog {
	display: flex;
	justify-content: space-between;
	align-items: center;
	.userLeft {
		width: 50%;
	}
	.userRight {
		width: 44%;
	}
	.userRight {
		padding-bottom: 3px;
	}
	.userCenter {
		> div:first-child {
			margin-bottom: 50px;
		}
		.el-icon-right,
		.el-icon-back {
			font-size: 30px !important;
		}
	}
}
.el-input__suffix:hover {
	display: none;
}
::v-deep .el-date-editor {
	height: 36px !important;
}
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 150px !important;
}
</style>
